<?php
declare(strict_types=1);
/**
 * Created by project.
 * User: huanzipap
 * Date: 2023/5/10
 * Time: 11:25
 */
namespace App\Controller\User;

use App\Controller\AppBaseController;
use App\Model\User;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\HttpServer\Annotation\Middleware;
use App\Middleware\WxApiAuth;

#[Controller(prefix: 'user')]
#[Middleware(WxApiAuth::class)]
class AuthController extends AppBaseController
{
    /**
     * 用户登录
     * @return object
     */
    #[RequestMapping(path:'login',methods: 'post,get')]
    public function login(): object
    {
        try{
            //获取用户信息
            $_user = $this->getUserSession();

            $auth_name = $this->request->input('auth_name',null);
            $auth_key = $this->request->input('auth_key',null);

            if(empty($auth_name) || empty($auth_key)){
                return $this->reMsg->re(0,'信息不能为空');
            }

            //查新用户信息状态
            $memberInfo = User::where(['auth_name'=>$auth_name,'auth_key'=>$auth_key])
                ->selectRaw('id,openid,nickname,avatar,auth_name,auth_key,auth_time,party_id,user_type')
                ->first();
            if(empty($memberInfo)) return $this->reMsg->re(0,'账号或密钥错误');
            if($memberInfo->auth_time) return $this->reMsg->re(0,'该账户已被认证');

            //判断当前微信号是否认证
            $readyInfo = User::where('openid',$_user->openid)->first();
            if($readyInfo) return $this->reMsg->re(0,'该微信号已认证');

            // 更新微信息
            $upData['openid']=$_user->openid;
            $upData['nickname']=$this->common->removeEmojiChar($_user->nickname);
            $upData['avatar']=$_user->avatar;
            $upData['auth_time'] = date('Y-m-d H:i:s',time());
            $upRet = User::where('id',$memberInfo->id)->update($upData);
            if($upRet){
                $_user->id = $memberInfo->id;
                $_user->party_id = $memberInfo->party_id;
                $_user->user_type = $memberInfo->user_type;
                $this->session->set('api_user',$_user);
                $this->session->save();
                return $this->reMsg->re(1,'success',$_user);
            }else{
                return $this->reMsg->re(0);
            }
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }



    /**
     * 用户登录
     * @return object
     * @throws \RedisException
     */
    #[RequestMapping(path:'loginBak',methods: 'post')]
    public function loginBak(): object
    {
        //获取用户信息
        $_user = $this->getUserSession();

        //验证用户信息
        $auth_name = $this->request->input('auth_name',null);
        $auth_key = $this->request->input('auth_key',null);
        $auth_phone = $this->request->input('auth_phone',null);
        $verify_code = $this->request->input('verify_code',null);
        if(empty($auth_name) ||
            empty($auth_key) ||
            empty($auth_phone) ||
            empty($verify_code)
        ) return $this->reMsg->re(0,'信息不能为空');

        $checkPhoneRet = $this->common->checkPhone($auth_phone);
        if($checkPhoneRet['status']==40002){
            return $this->reMsg->Re(0,$checkPhoneRet['message']);
        }

        //先去获取登录验证码
        $type = 'login';
        $verify_code_key = $type.'-'.$auth_phone;
        $verify_code_redis = $this->redis->hGet($this->redisPrefix.':verify_code',$verify_code_key);
        if($verify_code_redis==null) return $this->reMsg->re(0,'验证码失效');
        if($verify_code_redis!==$verify_code) return $this->reMsg->re(0,'验证码错误');

        //查新用户信息状态
        $memberInfo = User::where(['auth_name'=>$auth_name,'auth_key'=>$auth_key])->first();
        if(empty($memberInfo)) return $this->reMsg->re(0,'账号或密钥错误');
        if($memberInfo->auth_time) return $this->reMsg->re(0,'该账户已被认证');

        //判断当前微信号是否认证
        $readyInfo = User::where('openid',$_user->openid)->first();
        if($readyInfo) return $this->reMsg->re(0,'该微信号已认证',$_user);

        // 更新微信息
        $upData['openid']=$_user->openid;
        $upData['nickname']=$this->removeEmojiChar($_user->nickname);
        $upData['avatar']=$_user->avatar;
        $upData['auth_phone'] = $auth_phone;
        $upData['auth_time'] = date('Y-m-d H:i:s',time());
        $upRet = User::where('id',$memberInfo->id)->update($upData);
        if($upRet){
            //清除验证码
            $this->redis->hDel($this->redisPrefix.':verify_code',$verify_code_key);
            //将用户id存入session
            $_user->id = $memberInfo->id;
            $_user->party_id = $memberInfo->party_id;
            $_user->user_type = $memberInfo->user_type;
            $this->session->set('api_user',$_user);
            $this->session->save();
            return $this->reMsg->re(1);
        }else{
            return $this->reMsg->re(0);
        }
    }


    /**
     * 获取验证码
     * @param string $phone
     * @return object
     */
    #[RequestMapping(path: 'getVerifyCode/{phone}',methods: 'post,get')]
    public function getVerifyCode(string $phone): object
    {
        try{
            //获取用户信息
            $_user = $this->getUserSession();

            $checkPhoneRet = $this->common->checkPhone($phone);
            $checkPhoneRet = $this->common->checkPhone($phone);
            if($checkPhoneRet['status']==40002){
                return $this->reMsg->Re(0,$checkPhoneRet['message']);
            }

            $type = $this->request->input('type','login');
            if(empty($type) || !in_array($type,['login','bind'])) return $this->reMsg->Re(0,'非法获取验证码');

            //短信验证码key
            $verify_code_prefix = $this->redisPrefix.':verify_code';
            $verify_code_key = $type.'-'.$phone;

            //获取redis验证码是否存在
//            $verify_code = $this->redis->hGet($verify_code_prefix,$verify_code_key);
//            if($verify_code) return $this->reMsg->Re(0,'验证码已发送，请查看手机短信');

            //查询手机号是否已经被认证
            $userInfo = User::getUserInfoByPhone($phone);
            if($userInfo) return $this->reMsg->Re(0,'该手机号已被占用');

            //验证Ip地址，防止刷短信
            $verify_code_ip_prefix = $this->redisPrefix.':verify_code_ip';
            $verify_code_ip_key = $this->common->getClientIp();
            //查询改Ip是否存在
            $clientIpInfo = $this->redis->hGet($verify_code_ip_prefix,$verify_code_ip_key);
            $ip_count = 1;
            $verify_code_ip_value = time().'-'.$ip_count;
            if($clientIpInfo){
                $clientIpInfo = explode('-',$clientIpInfo);
                if(
                    isset($clientIpInfo[0]) &&
                    $clientIpInfo[0] &&
                    isset($clientIpInfo[1]) &&
                    $clientIpInfo[1]
                ){
                    $lastTime = $clientIpInfo[0] + 86400;
                    $ip_count = $clientIpInfo[1];
                    if($lastTime>time()){
                        //需要判断次数
//                        if($clientIpInfo[1]>=3) return $this->reMsg->Re(0,'请求验证码过于频繁，请稍后重试！');
                        $verify_code_ip_value = time().'-'.++$ip_count;
                    }
                }
            }
            //存储ip记录
            $this->redis->hSet($verify_code_ip_prefix,$verify_code_ip_key,$verify_code_ip_value);
            //设置验证码
            $verify_code = rand(100000,999999);
            $message = null;
            if($type==='bind'){
                $message = '账户绑定，验证码：'.$verify_code.'【活动工具箱】';
            }else if($type==='login'){
                $message = '账户登录，验证码：'.$verify_code.'【活动工具箱】';
            }else if($type==='register'){
                $message = '账户注册，验证码：'.$verify_code.'【活动工具箱】';
            }else if($type==='re_password'){
                $message = '账户找回密码，验证码：'.$verify_code.'【活动工具箱】';
            }else if($type==='order'){
                $message = '商品租赁订单，验证码：'.$verify_code.'【活动工具箱】';
            }else if($type==='card_order'){
                $message = '租赁卡订单，验证码：'.$verify_code.'【活动工具箱】';
            }else{
                return $this->reMsg->Re(0,'非法请求验证码');
            }
            $this->redis->hSet($this->redisPrefix.':verify_code', $verify_code_key,$verify_code);
//                return $this->reMsg->Re(0,$message,['verify_code'=>$verify_code]);
            $ret = $this->luosimao->sendMessage($phone,$message); //发送信息
            if($ret && $ret['error']==0){
                $this->redis->hSet($verify_code_prefix, $verify_code_key,$verify_code);
                return $this->reMsg->Re(1);
            }else{
                return $this->reMsg->Re(0,$ret['msg']);
            }
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }



    /**
     * @return object
     * @throws \RedisException
     */
    #[RequestMapping(path:'redisTest',methods:'get')]
    public function redisTest(): object
    {
        $this->redis->hSet('name', '1','11111');
        $this->redis->hSet('name', '2','22222');
        $all = $this->redis->hGetAll('name');
        return $this->reMsg->re(1,$all);
    }


}